import { Component, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesTreeNode } from '@shared/apes/core';
import { GridConfigService } from 'app/core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { Events } from '@core/services/events/Events';
import { Router } from '@angular/router';
import { ApesMessageService } from '@shared/apes/message';
import { UserAuthService } from '@core/services/user-auth.service';
import * as CryptoJS from 'crypto-js';
import { BiService } from '../../../bi.service';

@Component({
  selector: 'service-track',
  templateUrl: './service-track.component.html',
  styleUrls: ['./service-track.component.scss'],
})
export class ServiceTrackComponent implements OnInit {
  /* 按钮相关 */
  buttonBar = [{ hide: true, style: 'default', label: '查询', id: 'action_query', loading: false },
    { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
    { hide: true, style: 'default', label: '重置', id: 'action_reset' },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  getContextMenuItems: any;
  height: any = window.innerHeight - 255 + 'px';

  // 获取门店
  nxmdList: any[];
  arrNXMD = [];
  plList: any[];
  productData=[];

  // 报错样式
  hind: string = 'none';
  money: string = 'none';
  fullMoney: string = 'none';
  outTime: string = 'none';
  show: string = 'none';

  moneyMin: number;                    // 最小单品金额
  moneyMax: number;                    // 最大单品金额
  fullMoneyMin: number = 3000;         // 最小整单金额
  fullMoneyMax: number;                // 最大整单金额
  timeValueMin: number = 2;            // 最小耗时时长
  timeValueMax: number;                // 最大耗时时长
  days: any;                            // 日期的和

  // 查询条件
  fwNum: number;           // 服务单号
  fwfaNum: number;         // 服务方案号
  vipNum: number;          // 会员号
  carNum: string;          // 车牌号
  ngNXMD: any;              // 门店
  plID: any;                // 商品分类ID
  mdjcTime: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  endDate = null;          // 默认结束时间
  startDate = null;        // 默认开始时间
  checkAll: string = '0';   // 单选框

  userInfo = this.userAuthService.getUserInfoObj();
  companyId = this.userInfo.userAccount.post.company.id;
  companyData: any;
  companyList: any[];

  valueTree: string[] = [];
  expandKeys = [];

  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              private router: Router, private event: Events,
              private exportExcelService: ExportExcelService,
              private msg: ApesMessageService,
              private userAuthService: UserAuthService,
              private bi: BiService) {

    this.columnDefs = [

      { 'headerName': '车牌号', field: 'CPHM', width: 110, pinned: 'left' },
      { 'headerName': '门店', field: 'MDMC', width: 150 },
      { 'headerName': '会员卡号', field: 'VIPID' },
      { 'headerName': '会员姓名', field: 'VIPXM' },
      { 'headerName': '会员级别', field: 'VIPJBMC' },
      { 'headerName': '会员活跃度', field: 'VIPHYDMC' },
      { 'headerName': '服务单号', field: 'FWDH' },
      { 'headerName': '服务方案号', field: 'FWFAH' },
      { 'headerName': '服务类型', field: 'FWLXMC' },
      { 'headerName': '销售金额', field: 'XSJE' },
      { 'headerName': '状态', field: 'DJZT' },
      { 'headerName': '制单日期', field: 'ZDRQ_SJ' },
      { 'headerName': '审核日期', field: 'SHRQ_SJ' },
      { 'headerName': '确认日期', field: 'QRRQ_SJ' },
      { 'headerName': '质检日期', field: 'ZJRQ_SJ' },
      { 'headerName': '结算日期', field: 'JSRQ_SJ' },
      { 'headerName': '回执日期', field: 'HZRQ_SJ' },
      { 'headerName': '确认耗时', field: 'QRHS' },
      { 'headerName': '汽车厂牌', field: 'QCCPMC' },
      { 'headerName': '车型', field: 'CHXMC' },
      { 'headerName': '配置车型', field: 'PZCXMC' },
      { 'headerName': '备注', field: 'YXBZ' },
      { 'headerName': '终止日期', field: 'ZZRQ' },
      { 'headerName': '终止原因', field: 'ZZYY' },
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.getContextMenuItems = (params) => {
      let result = [
        'copy',
        'separator',
        { name: params.value },
        'separator',
        {
          name: '查看详情',
          action: () => {
            let dataModal = params.node.data;
            this.send(dataModal);
          },
        },
      ];
      return result;
    };
    this.companyList = [];
    this.companyList.push(this.companyId);
  }

  ngOnInit() {
    // 默认 请求 当天 数据
    this.endDate = new Date();
    this.startDate = new Date(this.endDate.getTime() - (0 * 24 * 60 * 60 * 1000));
    this.mdjcTime.push(this.startDate);
    this.mdjcTime.push(this.endDate);

    this.queryData();
    this.getNxmdData();
    this.getProductData();
    this.bi.getCompany(this.userInfo.userAccount.post.localPermit.id).then(value => {
      this.companyData = value;
    });

  }

  //跳转详情页
  send(params: any) {
    // this.data = params;
    // 加密传参
    let value = CryptoJS.enc.Utf8.parse(JSON.stringify(params));
    value = CryptoJS.enc.Base64.stringify(value);
    this.router.navigate(['/bi/car-info-details/carList/carListComponent'], { queryParams: { value: value } });
  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_export') {
        this.action_export();
      } else if (data.id === 'action_show') {
        this.action_show();
      }
    }
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, '服务单跟踪');
  }

  // 重置
  action_reset(): void {
    this.fwNum = null;
    this.fwfaNum = null;
    this.vipNum = null;
    this.carNum = null;
    this.ngNXMD = '';
    this.moneyMin = null;
    this.moneyMax = null;
    this.fullMoneyMin = 3000;
    this.fullMoneyMax = null;
    this.timeValueMin = 2;
    this.timeValueMax = null;
    this.mdjcTime = '';
    this.checkAll = '0';
  }

  // 展开查询条件
  action_show() {
    if (this.show === 'none') {
      this.show = 'flex';
    } else if (this.show === 'flex') {
      this.show = 'none';
    }
  }

  // 日期相减
  getTimeChang(d1, d2) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      if (this.days <= 31) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  // 查询按钮事件
  queryData() {
    this.rowData = [];
    this.getDate(this.mdjcTime, 'startValue', 'endValue');
    // 判断日期
    if (this.getTimeChang(this.endValue, this.startValue) === 'show') {
      this.hind = 'block';
    } else {
      // 判断日期不能为空
      if (this.startValue === null) {
        this.hind = 'block';
      } else {
        this.hind = 'none';
      }
    }
    // 判断单品金额
    if (this.getContrast(this.moneyMin, this.moneyMax) < 0) {
      this.money = 'block';
    } else {
      // 最小单品金额不能为负数
      if (this.moneyMin < 0) {
        this.money = 'block';
      } else {
        this.money = 'none';
      }
    }
    // 判断整单金额
    if (this.getContrast(this.fullMoneyMin, this.fullMoneyMax) < 0) {
      this.fullMoney = 'block';
    } else {
      // 判断整单金额不为空
      if (this.fullMoneyMin <= 0) {
        this.fullMoney = 'block';
      } else {
        this.fullMoney = 'none';
      }
    }

    // 判断耗时
    if (this.getContrast(this.timeValueMin, this.timeValueMax) < 0) {
      this.outTime = 'block';
    } else {
      // 判断最小耗时不能为空
      if (this.timeValueMin <= 0) {
        this.outTime = 'block';
      } else {
        this.outTime = 'none';
      }
    }

    //  必须满足以下条件才能调用接口
    if (this.outTime === 'none' && this.fullMoney === 'none' && this.money === 'none' && this.hind === 'none') {
      this.show = 'none';
      this.getTablesData();
    } else {
      this.show = 'flex';
    }
    this.buttonBar[0].loading = false;
  }

  onChange(param) {
    // console.log(this.valueTree);
  }

  getContrast(first: number, second: number) {
    if ((second - first) === -first) {
      if (second === 0) {
        return -1;
      } else {
        return 1;
      }
    } else if ((second - first) < 0) {
      return -1;
    } else {
      return 1;
    }
    ;
  }

  // 日期转换
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  getTablesData() {
    let data = {
      'interfaceMethod': 'ipmMgzzForAppService.getFWDGZ', 'pdata': {
        'FWDH': this.fwNum,
        'VIPID': this.vipNum,
        'FWFAH': this.fwfaNum,
        'CPHM': this.carNum,
        'MDID': this.ngNXMD,
        'PLID': this.valueTree,
        'STARTTIME': this.startValue,
        'ENDTIME': this.endValue,
        'DJZT': this.checkAll,
        'DPJESTART': this.moneyMin,
        'DPJEEND': this.moneyMax,
        'ZDJESTART': this.fullMoneyMin,
        'ZDJEEND': this.fullMoneyMax,
        'QRHSSTART': this.timeValueMin,
        'QRHSEND': this.timeValueMax,
        'companyId': this.companyList,
      },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.rowData = data;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取门店名称
  getNxmdData() {
    let data = {
      'interfaceMethod': 'ipmBPforAppService.getSQMDXX', 'pdata': { 'companyId': this.companyList },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.nxmdList = data;
            this.arrNXMD = this.nxmdList;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

  // 获取商品分类
  getProductData() {
    let data = {
      'interfaceMethod': 'ipmMgzzForAppService.getPLXX', 'pdata': {},
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        // debugger;
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.plList = data;
            this.productData = this.plList.map(item => {
              return new ApesTreeNode(item);
            });
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

}


